package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;

import cn.edu.sdjzu.xg23.kcsj01_backend.entity.EmployeeAssProject;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.Project;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.AbsAchievementMapper;

import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.EmployeeAssProjectMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.ProjectMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.ProjectService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private SnowflakeIdGenerator idGenerator;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private AbsAchievementMapper absAchievementMapper;
    @Autowired
    private EmployeeAssProjectMapper employeeAssProjectMapper;
    @Override
    @Transactional // 声明事务
    public boolean save(Project project) {
        Long sharedId = idGenerator.generateId();

        // 1. 插入 Achievement 相关记录
        absAchievementMapper.addAchievement(sharedId, "项目");

        // 2. 插入 Project 记录
        project.setId(sharedId);
        boolean success = projectMapper.insert(project);
        boolean insertSuccess = false;
        if (success && project.getApplicants() != null && !project.getApplicants().isEmpty()) {
            for (EmployeeAssProject applicant : project.getApplicants()) {
                applicant.setProject(new Project(sharedId));// 设置关联
            }

            insertSuccess  = employeeAssProjectMapper.insertApplicants(project.getApplicants());
        }
        return success&&insertSuccess;
    }

    @Override
    public  boolean deleteById(Long id) {
        return absAchievementMapper.deleteById(id);
    }

    @Override
    public void update(Project project) {
        projectMapper.update(project);
    }


    @Override
    public PageInfo<Project> selectProjectsByCondition(Integer pageNum, Integer pageSize, Project project, Long employeeId) {
        PageHelper.startPage(pageNum, pageSize);
        List<Project> projectList = projectMapper.selectProjectsByCondition(project,employeeId);
        return new PageInfo<>(projectList);
    }
    @Override
    public boolean approveProject(Project project) {
        return projectMapper.approveProject(project);
    }
}